package com.dididoctor.doctor.Activity.Order.DiagnosisSuggest;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dididoctor.doctor.Activity.PatientDetial.PatientDetialTHActivity;
import com.dididoctor.doctor.Bean.SuggestBean;
import com.dididoctor.doctor.MV.EduActivity;
import com.dididoctor.doctor.R;
import com.dididoctor.doctor.Utils.SharedPreferencesUtils;
import com.dididoctor.doctor.WYY.CustomAttachmentType;
import com.dididoctor.doctor.WYY.Medicaladvice.MedicaladviceAttachment;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by liying on 2016/4/25.
 */
public class DiagnosisSuggestActivity extends EduActivity implements View.OnFocusChangeListener, DiagnosisSuggestView {
    private TextView mTvSave;
    private LinearLayout mLayObservation, mLayDoctor, mLayMedication, mLayOther, mLinSuggest;
    private Button mBtnObservation, mBtnDoctor, mBtnMedication, mBtnOther;
    private Button[] mBtnMark = null;
    private EditText mEtObservation, mEtDoctor, mEtMedication, mEtOther, mEtDiagnosisSuggest;
    private EditText[] mEtContent = null;
    private TextView mTvSurvey, mTvSeedoctor, mTvPharmacy, mTvOther;
    private boolean isObservation = false;
    private boolean isDoctor = false;
    private boolean isMedication = false;
    private boolean isOther = false;
    private boolean[] isChoice = null;
    public static final int OBSERVATION_CODE = 10001;
    public static final int DOCTOR_CODE = 10002;
    public static final int MEDICATION_CODE = 10003;
    public static final int OTHER_CODE = 10004;
    private View focusView;

    private DiagnosisSuggestPresenter mPresenter;
    private String content;
    private List<DiagnosisSuggestBean> datas = new ArrayList<DiagnosisSuggestBean>();
    private String recId = "";
    private String disId = "";
    private String suggest = "";
    private String sex = "";
    private String GuesspatientName;
    private String Guessage;
    private String GuessillName;
    private String accId;
    private String GuesspatientHeadPic;

    @Override
    public void init() {
        recId = getIntent().getStringExtra("recId");
        disId = getIntent().getStringExtra("disId");
        GuesspatientName = getIntent().getStringExtra("patientName");
        Guessage = getIntent().getStringExtra("age");
        GuessillName = getIntent().getStringExtra("illName");
        GuesspatientHeadPic = getIntent().getStringExtra("patientHeadPic");
        sex = getIntent().getStringExtra("sex");
        accId = getIntent().getStringExtra("accId");
        initView();

    }

    @Override
    public void onClickEvent(View view) {
        Intent intent = new Intent(DiagnosisSuggestActivity.this, SuggestListActivity.class);
        intent.putExtra("disId", disId);
        switch (view.getId()) {
            case R.id.tv_finish:
                mTvSave.setEnabled(false);
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        mTvSave.setEnabled(true);
                    }
                }, 3000);
                if (checkValue()) {
                    setListData();
                }

                break;
            case R.id.lay_observation:
                startActivityForResult(intent, OBSERVATION_CODE);
                break;
            case R.id.lay_doctor:
                startActivityForResult(intent, DOCTOR_CODE);
                break;
            case R.id.lay_medication:
                startActivityForResult(intent, MEDICATION_CODE);
                break;
            case R.id.lay_other:
                startActivityForResult(intent, OTHER_CODE);
                break;
            case R.id.btn_observation:
                if ("".equals(mEtObservation.getText().toString().trim())) {
                    setEtFcous(0);
                }

                break;
            case R.id.btn_doctor:
                if ("".equals(mEtDoctor.getText().toString().trim())) {
                    setEtFcous(1);
                }
                break;
            case R.id.btn_medication:
                if ("".equals(mEtMedication.getText().toString().trim())) {
                    setEtFcous(2);
                }
                break;
            case R.id.btn_other:
                if ("".equals(mEtOther.getText().toString().trim())) {
                    setEtFcous(3);
                }
                break;
        }
    }

    @Override
    public void setContentLayout() {
        setContentView(R.layout.activity_diagnosis_suggest);
    }

    private void initView() {
        ((TextView) findViewById(R.id.tv_title)).setText("诊疗建议");
        mTvSave = (TextView) findViewById(R.id.tv_finish);
        mTvSave.setVisibility(View.VISIBLE);
        mTvSave.setText("保存");
        mTvSave.setOnClickListener(this);
        mLayObservation = (LinearLayout) findViewById(R.id.lay_observation);
        mLayObservation.setOnClickListener(this);
        mLayDoctor = (LinearLayout) findViewById(R.id.lay_doctor);
        mLayDoctor.setOnClickListener(this);
        mLayMedication = (LinearLayout) findViewById(R.id.lay_medication);
        mLayMedication.setOnClickListener(this);
        mLayOther = (LinearLayout) findViewById(R.id.lay_other);
        mLayOther.setOnClickListener(this);
        mLinSuggest = (LinearLayout) findViewById(R.id.lin_suggest);

        //观察
        mTvSurvey = (TextView) findViewById(R.id.tv_survey);
        mBtnObservation = (Button) findViewById(R.id.btn_observation);
        mBtnObservation.setOnClickListener(this);
        //就诊
        mTvSeedoctor = (TextView) findViewById(R.id.tv_seedoctor);
        mBtnDoctor = (Button) findViewById(R.id.btn_doctor);
        mBtnDoctor.setOnClickListener(this);
        //用药
        mTvPharmacy = (TextView) findViewById(R.id.tv_pharmacy);
        mBtnMedication = (Button) findViewById(R.id.btn_medication);
        mBtnMedication.setOnClickListener(this);
        //其他
        mTvOther = (TextView) findViewById(R.id.tv_other);
        mBtnOther = (Button) findViewById(R.id.btn_other);
        mBtnOther.setOnClickListener(this);

        mEtObservation = (EditText) findViewById(R.id.et_observation);
        mEtObservation.setOnFocusChangeListener(this);
        mEtDoctor = (EditText) findViewById(R.id.et_doctor);
        mEtDoctor.setOnFocusChangeListener(this);
        mEtMedication = (EditText) findViewById(R.id.et_medication);
        mEtMedication.setOnFocusChangeListener(this);
        mEtOther = (EditText) findViewById(R.id.et_other);
        mEtOther.setOnFocusChangeListener(this);
        mEtDiagnosisSuggest = (EditText) findViewById(R.id.et_diagnosis_suggest);
        mEtDiagnosisSuggest.setOnFocusChangeListener(this);

        mBtnMark = new Button[]{mBtnObservation, mBtnDoctor, mBtnMedication, mBtnOther};
        mEtContent = new EditText[]{mEtObservation, mEtDoctor, mEtMedication, mEtOther};
        for (int x = 0; x < mBtnMark.length; x++) {
            mBtnMark[x].setBackgroundResource(R.drawable.rounded_rectangle_hollow_gray);
            mBtnMark[x].setTextColor(Color.parseColor("#dddddd"));
        }
        for (int x = 0; x < mBtnMark.length; x++) {
            mEtContent[x].setBackgroundResource(R.drawable.et_login_wihte);
            mEtContent[x].setEnabled(false);
        }

        isChoice = new boolean[]{isObservation, isDoctor, isMedication, isOther};

        focusView = findViewById(R.id.view_focus);
        focusView.setFocusable(true);
        focusView.setFocusableInTouchMode(true);
        focusView.requestFocus();
        focusView.requestFocusFromTouch();

        mPresenter = new DiagnosisSuggestPresenter(DiagnosisSuggestActivity.this, DiagnosisSuggestActivity.this);
        mPresenter.getadviceper(disId);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            SuggestBean bean = (SuggestBean) data.getSerializableExtra("data");
            if (bean != null) {
                if (requestCode == OBSERVATION_CODE) {
                    setData(0, bean);
                }

                if (requestCode == DOCTOR_CODE) {
                    setData(1, bean);
                }

                if (requestCode == MEDICATION_CODE) {
                    setData(2, bean);
                }

                if (requestCode == OTHER_CODE) {
                    setData(3, bean);
                }
            }
        }


        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.et_observation:
                setEtBg(0);
//                setEtFcous(0);
                break;
            case R.id.et_doctor:
                setEtBg(1);
//                setEtFcous(1);
                break;
            case R.id.et_medication:
                setEtBg(2);
//                setEtFcous(2);
                break;
            case R.id.et_other:
                setEtBg(3);
//                setEtFcous(3);
                break;
            case R.id.et_diagnosis_suggest:
                setEtBg(4);
                break;
        }
    }


    //为医生建议设置内容
    public void setData(int i, SuggestBean bean) {
        isChoice[i] = false;
        setEtFcous(i);
        mEtContent[i].setText(bean.getContent());

    }

    //更改ET的背景图片
    public void setEtBg(int tag) {
        for (int i = 0; i < mEtContent.length; i++) {
            if (i == tag) {
                mEtContent[i].setBackgroundResource(R.drawable.et_login_orange);
            } else {
                mEtContent[i].setBackgroundResource(R.drawable.et_login_wihte);
            }
        }
    }

    //设置被选中按钮的颜色
    public void setEtFcous(int tag) {
        isChoice[tag] = !isChoice[tag];
        for (int i = 0; i < mEtContent.length; i++) {
            if (i == tag) {
                if (isChoice[i]) {
                    mEtContent[i].requestFocus();
                    mEtContent[i].setEnabled(true);
                    mBtnMark[i].setBackgroundResource(R.drawable.rounded_rectangle_yellow);
                    mBtnMark[i].setTextColor(Color.parseColor("#ffffff"));
                } else {
                    mEtContent[i].setBackgroundResource(R.drawable.et_login_wihte);
                    mEtContent[i].setEnabled(false);
                    mBtnMark[i].setBackgroundResource(R.drawable.rounded_rectangle_hollow_gray);
                    mBtnMark[i].setTextColor(Color.parseColor("#dddddd"));
                }
            } else {
                isChoice(isChoice[i], i);
            }
        }
    }

    //设置根据其他按钮的修改ET的可编辑状态和按钮的背景
    public void isChoice(boolean boo, int i) {
        if (boo) {
            mEtContent[i].setEnabled(true);
            mBtnMark[i].setBackgroundResource(R.drawable.rounded_rectangle_yellow);
            mBtnMark[i].setTextColor(Color.parseColor("#ffffff"));
        } else {
            mEtContent[i].setEnabled(false);
            mBtnMark[i].setBackgroundResource(R.drawable.rounded_rectangle_hollow_gray);
            mBtnMark[i].setTextColor(Color.parseColor("#dddddd"));
        }
    }


    public boolean checkValue() {
        content = mEtDiagnosisSuggest.getText().toString().trim();
        String observation = mEtObservation.getText().toString().trim();
        String doctor = mEtDoctor.getText().toString().trim();
        String medication = mEtMedication.getText().toString().trim();
        String other = mEtOther.getText().toString().trim();

        if (content == null || "".equals(content)) {
            showToastMessage("诊断结果不能为空");
            return false;
        }

        if ("".equals(observation) && "".equals(doctor) && "".equals(medication) && "".equals(other)) {
            showToastMessage("诊断建议不能为空");
            return false;
        }
        return true;
    }

    @Override
    public void getDataFail() {
        showToastMessage("保存诊断建议失败");
    }

    @Override
    public void getDataSucced() {

        MedicaladviceAttachment attachment = new MedicaladviceAttachment(CustomAttachmentType.MEDICCALADVICE);

        attachment.setPatientName(GuesspatientName);

        attachment.setAge(Guessage);
        attachment.setIllName(GuessillName);
        attachment.setPatientHeadPic(GuesspatientHeadPic);
        attachment.setRecId(recId);
        attachment.setDisId(disId);
        attachment.setSuggestion(suggest);
        attachment.setSuggestionResult(content);
        attachment.setMessageAttachType(CustomAttachmentType.MEDICCALADVICE + "");
        attachment.setSex(sex);
        IMMessage message;

        message = MessageBuilder.createCustomMessage(accId, SessionTypeEnum.P2P, "", attachment);
        NIMClient.getService(MsgService.class).sendMessage(message, true);

//        Intent intent = new Intent();
//        intent.setAction("com.medicaladvice");
//        intent.putExtra("msgType", "Diaoprocessed");


        Intent PDAintent = new Intent(DiagnosisSuggestActivity.this, PatientDetialTHActivity.class);
        String medicaladvice_use_clientId = SharedPreferencesUtils.getParam(DiagnosisSuggestActivity.this, "Medicaladvice_use_clientId", "0");
        String medicaladvice_use_isSign = SharedPreferencesUtils.getParam(DiagnosisSuggestActivity.this, "Medicaladvice_use_isSign", "0");
        String medicaladvice_use_isCallorpictury = SharedPreferencesUtils.getParam(DiagnosisSuggestActivity.this, "Medicaladvice_use_isCallorpictury", "0");
//          1-即时咨询 2-电话咨询
        if ("1".equals(medicaladvice_use_isCallorpictury)) {
            PDAintent.putExtra("status", "2");
//            intent.putExtra("upDataOrderStatus", "2");

        } else {
            PDAintent.putExtra("status", "3");
//            intent.putExtra("upDataOrderStatus", "3");
        }
//        sendBroadcast(intent);
        PDAintent.putExtra("clientId", medicaladvice_use_clientId);
        PDAintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PDAintent.putExtra("isSign", medicaladvice_use_isSign);
        PDAintent.putExtra("accId", accId);
        PDAintent.putExtra("isCallorpictury", medicaladvice_use_isCallorpictury);
        PDAintent.putExtra("CurrentTab", 1);
        startActivity(PDAintent);
//        Intent intent = new Intent();
//        intent.putExtra(Extras.EXTRA_ACCOUNT, accId);
//        intent.putExtra(Extras.EXTRA_CUSTOMIZATION, SessionHelper.getP2pCustomization(accId));
//        intent.setClass(DiagnosisSuggestActivity.this, P2PMessageActivity.class);
//        intent.putExtra("rank", "1");
//        intent.putExtra("isCallorpictury", "1");
////          FLAG_ACTIVITY_SINGLE_TOP
//        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);

        finish();

    }


    /**
     * 根据用户生日计算年龄
     */
    public static int getAgeByBirthday(Date birthday) {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthday)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }

        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);

        cal.setTime(birthday);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH) + 1;
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                // monthNow==monthBirth
                if (dayOfMonthNow < dayOfMonthBirth) {
                    age--;
                }
            } else {
                // monthNow>monthBirth
                age--;
            }
        }
        return age;
    }


    public void setListData() {
        for (int i = 0; i < isChoice.length; i++) {
            if (isChoice[i]) {
                DiagnosisSuggestBean bean = new DiagnosisSuggestBean();
                bean.setType(i + 1 + "");
                if (i + 1 == 1) {
                    suggest += "观察,";
                } else if (i + 1 == 2) {
                    suggest += "就诊,";
                } else if (i + 1 == 3) {
                    suggest += "用药,";
                } else if (i + 1 == 4) {
                    suggest += "其他,";
                }
                bean.setContent(mEtContent[i].getText().toString().trim());
                datas.add(bean);
            }
        }
        mPresenter.updateSuggest(recId, content, datas);
    }

    @Override
    public void getAdviceper(List<DiagnosisSuggestBean> beans, String show) {
        if ("0".equals(show)) {
            mLinSuggest.setVisibility(View.GONE);
        } else {
            mLinSuggest.setVisibility(View.VISIBLE);
            for (int i = 0; i < beans.size(); i++) {
                DiagnosisSuggestBean bean = beans.get(i);
                if ("1".equals(bean.getType())) {
                    mTvSurvey.setText(bean.getContent() + "%的医生建议观察");
                } else if ("2".equals(bean.getType())) {
                    mTvSeedoctor.setText(bean.getContent() + "%的医生建议就诊");
                } else if ("3".equals(bean.getType())) {
                    mTvPharmacy.setText(bean.getContent() + "%的医生建议用药");
                } else if ("4".equals(bean.getType())) {
                    mTvOther.setText(bean.getContent() + "%的医生建议其他");
                }
            }
        }
    }

}
